package com.javer.dao.support;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.util.Assert;

import com.javer.domain.PageView;

public class DataSourceDaoSupport {
	protected JdbcTemplate jdbcTemplate;

	protected JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	@Autowired
	protected void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	@PostConstruct
	protected void afterPropertiesSet() {
		Assert.notNull(jdbcTemplate, "jdbcTemplate must not be null.");
	}
	
	public PageView getByPage(PageView pv, String countSql, Object[] args1, String listSql, Object[] args2, RowMapper mapper) {
		Assert.notNull(pv, "pageView must not be null");
		int count = jdbcTemplate.queryForInt(countSql != null ? countSql : "select count(*) from " + pv.getTableName(), args1);
		int start = (pv.getPageNo() - 1) * pv.getPageSize();
		int pageCount = count / pv.getPageSize();
		pageCount += count % pv.getPageSize() == 0 ? 0 : 1;
		
		String sql = listSql != null ? listSql : "select * from "+ pv.getTableName() +" order by id desc";
		sql += " limit "+ start +", " + pv.getPageSize();
		
		pv.setRecords(jdbcTemplate.query(sql, args2, mapper != null ? mapper : getMapper()));
		pv.setCount(count).setPageCount(pageCount);
		return pv;
	}
	
	public PageView getByPage(PageView pv, String countSql, String listSql, RowMapper mapper) {
		return getByPage(pv, countSql, null, listSql, null, mapper);
	}
	
	public PageView getByPage(PageView pv, String countSql, String listSql) {
		return getByPage(pv, countSql, null, listSql, null, null);
	}
	
	public PageView getByPage(PageView pv) {
		return getByPage(pv, null, null, null, null, null);
	}
	
	protected RowMapper getMapper() {
		throw new IllegalStateException("Child class must override getMapper() method");
	}
	
}
